#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test script to verify the UNIQUE(name, type) constraint fix
"""

import sqlite3
import sys
import tempfile
import os
from pathlib import Path

# Add the extractor directory to the path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from uma_ukm_extractor import DatabaseManager, HistogramInfo, EnumInfo, UKMEventInfo


def test_unique_constraint():
    """Test the UNIQUE(name, type) constraint fix."""

    # Create a temporary database
    with tempfile.NamedTemporaryFile(suffix='.db', delete=False) as temp_file:
        temp_db = temp_file.name

    try:
        print(f"Testing with temporary database: {temp_db}")

        # Create database manager
        db_manager = DatabaseManager(temp_db)
        db_manager.connect()
        db_manager.create_tables()

        print("✅ Database tables created successfully")

        # Test 1: Insert same name with different types (should work)
        print("\n🧪 Test 1: Same name, different types")

        histogram_info = HistogramInfo(
            name="TestMetric",
            summary="A test histogram",
            file_path="test/file1.xml",
            line_number=10,
            owners=["test@example.com"]
        )

        enum_info = EnumInfo(
            name="TestMetric",  # Same name!
            summary="A test enum",
            file_path="test/file2.xml",
            line_number=20,
            owners=["test@example.com"],
            values=[(0, "VALUE1", None), (1, "VALUE2", None)]
        )

        # Insert histogram
        hist_id = db_manager.insert_histogram(histogram_info)
        print(f"✅ Inserted histogram with ID: {hist_id}")

        # Insert enum with same name but different type (should work)
        enum_id = db_manager.insert_enum(enum_info)
        print(f"✅ Inserted enum with same name but different type, ID: {enum_id}")

        # Test 2: Insert same name with same type (should fail gracefully)
        print("\n🧪 Test 2: Same name, same type (should update existing)")

        duplicate_hist = HistogramInfo(
            name="TestMetric",  # Same name
            summary="Updated histogram summary",  # Different summary
            file_path="test/file3.xml",
            line_number=30,
            owners=["updated@example.com"]
        )

        # This should update the existing record, not create a duplicate
        duplicate_hist_id = db_manager.insert_histogram(duplicate_hist)
        print(f"✅ Inserted duplicate histogram, got same ID: {duplicate_hist_id}")

        # Verify the data was updated
        conn = sqlite3.connect(temp_db)
        cursor = conn.cursor()

        cursor.execute("SELECT COUNT(*) FROM metrics WHERE name = 'TestMetric' AND type = 'histogram'")
        hist_count = cursor.fetchone()[0]
        print(f"✅ Histogram count: {hist_count} (should be 1)")

        cursor.execute("SELECT COUNT(*) FROM metrics WHERE name = 'TestMetric' AND type = 'enum'")
        enum_count = cursor.fetchone()[0]
        print(f"✅ Enum count: {enum_count} (should be 1)")

        # Verify summary was updated
        cursor.execute("SELECT summary FROM metrics WHERE name = 'TestMetric' AND type = 'histogram'")
        updated_summary = cursor.fetchone()[0]
        print(f"✅ Updated histogram summary: {updated_summary}")

        # Test the unique constraint directly
        print("\n🧪 Test 3: Direct constraint test")

        try:
            # This should fail due to the UNIQUE(name, type) constraint
            cursor.execute("""
                INSERT INTO metrics (name, type, summary, file_path, line_number)
                VALUES ('TestMetric', 'histogram', 'Should fail', 'test.xml', 1)
            """)
            print("❌ ERROR: Duplicate insertion should have failed!")
            return False
        except sqlite3.IntegrityError as e:
            if "UNIQUE constraint failed" in str(e):
                print("✅ UNIQUE constraint working correctly!")
            else:
                print(f"❌ Unexpected error: {e}")
                return False

        conn.close()
        db_manager.close()

        print("\n🎉 All tests passed! The UNIQUE(name, type) constraint fix is working correctly.")
        return True

    except Exception as e:
        print(f"❌ Test failed: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        # Clean up
        if os.path.exists(temp_db):
            os.unlink(temp_db)
            print(f"🧹 Cleaned up temporary database: {temp_db}")


if __name__ == "__main__":
    print("Testing UNIQUE(name, type) constraint fix...")
    print("=" * 50)

    success = test_unique_constraint()

    if success:
        print("\n✅ All tests passed!")
        sys.exit(0)
    else:
        print("\n❌ Tests failed!")
        sys.exit(1)